package com.xzh.gulimall.member.service.impl;

import com.xzh.gulimall.member.dao.MemberLevelDao;
import com.xzh.gulimall.member.entity.MemberLevelEntity;
import com.xzh.gulimall.member.exception.PhoneExistException;
import com.xzh.gulimall.member.exception.UsernameExistException;
import com.xzh.gulimall.member.vo.MemberLoginVo;
import com.xzh.gulimall.member.vo.MemberRegistVo;
import com.xzh.gulimall.member.vo.SocialUser;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzh.common.utils.PageUtils;
import com.xzh.common.utils.Query;

import com.xzh.gulimall.member.dao.MemberDao;
import com.xzh.gulimall.member.entity.MemberEntity;
import com.xzh.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity memberEntity = new MemberEntity();
        //设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());


        //检查用户名和手机是否唯一,为了让controller感知异常，使用异常机制
        checkphoneUnque(vo.getPhone());
        checkUsernameUnque(vo.getUserName());
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setNickname(vo.getUserName());

        //密码要进行加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);

        //保存
        baseMapper.insert(memberEntity);
    }
    
    @Override
    public void checkphoneUnque(String phone) throws PhoneExistException{
        Long mobile = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(mobile>0){
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnque(String userName) throws UsernameExistException{
        Long count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if(count>0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct)
                .or().eq("mobile", loginacct));
        if(memberEntity==null){
            return null;
        }else{
            String oldPassword = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, oldPassword);
            if(matches){
                //登录成功
                return memberEntity;
            }else{
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) {
        //具有登录和注册合并逻辑
        Integer u_id = socialUser.getU_id();
        MemberEntity memberEntity1 = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("u_id", u_id));
        if(memberEntity1!=null){
            //这个用户已经注册了
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity1.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());
            //更新最新accessToken 和 expiresIn
            baseMapper.updateById(update);

            memberEntity1.setAccessToken(socialUser.getAccess_token());
            memberEntity1.setExpiresIn(socialUser.getExpires_in());
            return memberEntity1;
        }else {
            //没有查到当前社交用户对应的记录，注册一个
            MemberEntity regist = new MemberEntity();
            regist.setNickname(socialUser.getUserName());
            regist.setUId(socialUser.getU_id());
            regist.setAccessToken(socialUser.getAccess_token());
            regist.setExpiresIn(socialUser.getExpires_in());
            baseMapper.insert(regist);
            return regist;
        }
    }

}